package org.geektimes.configuration.microprofile.config.source;

import org.apache.commons.configuration2.JNDIConfiguration;
import org.apache.commons.configuration2.builder.BasicConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.JndiBuilderParameters;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.eclipse.microprofile.config.spi.ConfigSource;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: menglinggang
 * @Date: 2021-03-17
 * @Time: 2:26 下午
 */
public class ApacheCommonConfigSource implements ConfigSource {


    private final JNDIConfiguration config;

    public ApacheCommonConfigSource() {
        Parameters params = new Parameters();
        Context root = null;
        try {
            root = InitialContext.doLookup("java:comp/env");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        JndiBuilderParameters jndiBuilderParameters = params.jndi().setContext(root).setPrefix("").setThrowExceptionOnMissing(false);

        BasicConfigurationBuilder<JNDIConfiguration> builder =
                new BasicConfigurationBuilder<>(JNDIConfiguration.class).configure(jndiBuilderParameters);
        try {
            config = builder.getConfiguration();
        } catch (ConfigurationException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Set<String> getPropertyNames() {
        Set<String> names = new HashSet<>();
        while (config.getKeys().hasNext()) {
            String name = config.getKeys().next();
            names.add(name);
        }
        return names;
    }

    @Override
    public String getValue(String s) {
        return config.getString(s);
    }

    @Override
    public String getName() {
        return "JNDI source";
    }
}
